import {
  dictPageApi,
  addDictApi,
  editDictApi,
  delDictApi
} from '@/api/system/dict'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { DictModel } from '@/api/model/dictModel'

type props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  drawerShow: Ref<boolean>
  dictForm: Ref<Partial<DictModel>>
  proTableInst: Ref<ProTableInst | null>
}

export const useDictApi = ({
  handleType,
  handleTag,
  drawerShow,
  dictForm,
  proTableInst
}: props) => {
  const confirmLoading = ref(false)

  // 获取字典列表
  const fetchDictPage = async (pageRequest: PageRequest, queryParams) => {
    try {
      const res = await dictPageApi({
        ...queryParams,
        pageRequest
      })

      if (res.code === '0000') {
        return {
          data: res.data?.content,
          total: res.data?.total
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  // 新增or修改字典
  const fetchAddOrEditDict = async () => {
    try {
      confirmLoading.value = true
      const fetch = handleType.value === 'add' ? addDictApi : editDictApi
      const res = await fetch({
        ...dictForm.value
      })
      if (res.code === '0000') {
        window['$message'].success(handleTag.value + '成功')
        proTableInst.value?.reload()
        drawerShow.value = false
      }
    } catch (e) {
      console.log(e)
    } finally {
      confirmLoading.value = false
    }
  }

  // 删除字典
  const fetchDelDict = async (id) => {
    try {
      const res = await delDictApi({ id })
      if (res.code === '0000') {
        window['$message'].success('删除成功')
        proTableInst.value?.reload()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    fetchDictPage,
    fetchAddOrEditDict,
    fetchDelDict
  }
}
